<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { adminApi } from '../../api'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const form = reactive({
  id: '',
  username: '',
  password: '',
  email: '',
  phone: '',
  status: 1,
  roleIds: []
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 角色选项
const roleOptions = ref([])

// 获取角色列表
const fetchRoleOptions = async () => {
  try {
    const res = await adminApi.getRoles()
    console.log('角色API返回数据:', res)
    
    // 检查数据结构
    if (Array.isArray(res)) {
      roleOptions.value = res.map(role => ({
        id: role.id,
        name: role.name
      }))
    } else if (res && Array.isArray(res.list)) {
      // 如果返回的是包含list的对象
      roleOptions.value = res.list.map(role => ({
        id: role.id,
        name: role.name
      }))
    } else {
      // 如果数据结构不符合预期，记录警告
      console.warn('角色API返回数据结构与预期不符:', res)
      roleOptions.value = []
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 表单引用
const formRef = ref()

// 初始化数据
onMounted(() => {
  fetchData()
  fetchRoleOptions()
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      username: searchForm.username || undefined,
      nickname: searchForm.email || undefined,
      status: searchForm.status !== '' ? parseInt(searchForm.status) : undefined
    }
    console.log('发送请求参数:', params)
    const res = await adminApi.getAdminList(params)
    console.log('API返回数据:', res)
    
    // 检查数据结构
    if (res && Array.isArray(res.list)) {
      tableData.value = res.list
      pagination.total = res.total || 0
    } else if (Array.isArray(res)) {
      // 如果直接返回数组
      tableData.value = res
      pagination.total = res.length || 0
    } else {
      // 如果数据结构不符合预期，记录警告
      console.warn('API返回数据结构与预期不符:', res)
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    ElMessage.error('获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加管理员'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 显示编辑对话框
const showEditDialog = (row: any) => {
  dialogTitle.value = '编辑管理员'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  form.id = row.id
  form.username = row.username
  form.email = row.email
  form.phone = row.phone
  form.status = row.status
  // 编辑时不显示密码
  form.password = ''
}

// 删除管理员
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该管理员吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await adminApi.deleteAdmin(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.error('删除管理员失败:', error)
      ElMessage.error('删除管理员失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑管理员
          await adminApi.updateAdmin({
            id: form.id,
            username: form.username,
            nickname: form.username, // 使用username作为nickname
            email: form.email,
            phone: form.phone,
            status: form.status,
            roleIds: form.roleIds
          })
          ElMessage.success('编辑成功')
        } else {
          // 添加管理员
          await adminApi.addAdmin({
            username: form.username,
            password: form.password,
            nickname: form.username, // 使用username作为nickname
            email: form.email,
            phone: form.phone,
            status: form.status,
            roleIds: form.roleIds
          })
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error(isEdit.value ? '编辑管理员失败:' : '添加管理员失败:', error)
        ElMessage.error(isEdit.value ? '编辑管理员失败' : '添加管理员失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = ''
  form.username = ''
  form.password = ''
  form.email = ''
  form.phone = ''
  form.status = 1
  form.roleIds = []
}

// 状态格式化
const statusFormatter = (row: any) => {
  return row.status === 1 ? '启用' : '禁用'
}

// 重置密码对话框控制
const resetPasswordDialogVisible = ref(false)
const resetPasswordForm = reactive({
  id: '',
  newPassword: '',
  confirmPassword: ''
})

// 重置密码表单验证规则
const resetPasswordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 重置密码表单引用
const resetPasswordFormRef = ref()

// 重置密码
const handleResetPassword = (row: any) => {
  resetPasswordForm.id = row.id
  resetPasswordForm.newPassword = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordDialogVisible.value = true
}

// 状态标签类型
const statusTagType = (status: number) => {
  return status === 1 ? 'success' : 'danger'
}

// 提交重置密码表单
const submitResetPassword = () => {
  resetPasswordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (resetPasswordForm.newPassword !== resetPasswordForm.confirmPassword) {
        ElMessage.error('两次输入的密码不一致')
        return
      }
      
      try {
        await adminApi.resetPassword({
          id: resetPasswordForm.id,
          password: resetPasswordForm.newPassword
        })
        ElMessage.success('密码重置成功')
        resetPasswordDialogVisible.value = false
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error('重置密码失败')
      }
    }
  })
}
</script>

<template>
  <div class="admin-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加管理员</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="roles" label="角色" width="120">
          <template #default="{ row }">
            <el-tag v-for="(role, index) in row.roles" :key="index" size="small" style="margin-right: 5px;">
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handleResetPassword(row)">重置密码</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="400px"
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="80px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请确认新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitResetPassword">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.admin-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

/* 搜索区域样式优化 */
.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 增加选择框宽度 */
.search-card .el-select {
  width: 150px;
}

.operation-area {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>